package com.podcstr.dao;

import com.podcstr.entity.Category;
import org.apache.log4j.Logger;

import javax.persistence.NoResultException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author azim
 * @since 5/16/13 
 */
public class CategoryDaoImpl extends GenericDaoImpl<Category, Long> implements CategoryDao {

    private final Logger log = Logger.getLogger(UserDaoImpl.class);

    @Override
    public Category findCategoryByName(String categortName) {

        Category category = null;

        try {

            category = (Category) (getEntityManager().createNamedQuery("tb_categories.findByCategoryName").setParameter("name", categortName).getSingleResult());
        } catch (NoResultException noe) {

            category = null;
        }

        if (category != null) {
            log.info(new Date() + " : Returning category with name : " + categortName);
        }
        return category;
    }

    @Override
    public List<Category> fingParentCategories() {

        List<Category> categories = getEntityManager().createNamedQuery("tb_categories.findParentCategories").getResultList();

        if (categories.size() != 0) {
            log.info(new Date() + " : Returning list of parent categories.");
        } else {
            categories = new ArrayList<Category>();
        }
        return categories;
    }

    @Override
    public List<Category> fingChildCategories(Long parentId) {

        List<Category> categories = getEntityManager().createNamedQuery("tb_categories.findChildCategories").setParameter("parent", parentId).getResultList();

        if (categories.size() != 0) {
            log.info(new Date() + " : Returning list of child categories with paen id : " + parentId + ".");
        } else {
            categories = new ArrayList<Category>();
        }
        return categories;
    }
}
